const nodemailer = require("nodemailer");
const fs = require("fs-extra");

/**
 * 参考文章
 * https://www.cnblogs.com/goloving/p/12491923.html
 * */

let transporter;
let from;
let canUse = null;

async function init() {
    return new Promise(r => {
        if (canUse !== null) return r();
        transporter = nodemailer.createTransport(NCUTCAT.localProperty.email_data);
        from = `NCUT CAT <${NCUTCAT.localProperty.email_data.auth.user}>`;
        transporter.verify(error => {
            canUse = !error;
            if (error) NCUTCAT.error(`MailManager - ${"无法加载".red} - ${error}`);
            else NCUTCAT.infoLog("MailManager", "成功加载");
            r();
        });
    })
}
let emails = {};
let watcher = {};

function getEmail(name) {
    let cache = emails[name];
    if (cache) return cache;
    let fn = `model/mail/${name}.html`;
    cache = fs.readFileSync(fn).toString();
    emails[name] = cache;
    if (!watcher[name]) watcher[name] = fs.watch(fn, () => delete emails[name]);
    return cache;
}

module.exports.sendVerifyEmail = async (to, code) => {
    return new Promise(async r => {
        await init();
        if (!canUse) return r("Bot账户异常");
        if (!to || !code) throw new Error('bad data');
        let text = getEmail('Verify');
        text = text.replace("${code}", code);
        let mailOptions = {
            from: from,
            to: to,
            subject: '验证邮件',
            text: '注册验证 VerifyEmai',
            html: text
        };
        transporter.sendMail(mailOptions, err => r(err));
    });
}